import {get, reduce} from 'lodash';

const MIN_TIME = 100;
const Max_Time = 10 * 60 * 60 * 1000;
const _cache = {};

/**
 * 缓存action
 * @param key 数据存储路径
 * @param action 缓存对象
 * @return {function(*, *)}
 */
export default (module, key, action, ops) => (dispatch, getState) => {
    const now = new Date();
    const cacheKey = module + '_' + key;
    const cacheInfo = _cache[cacheKey] || (_cache[cacheKey] = {});
    if (cacheInfo.last && now - cacheInfo.last < MIN_TIME) {
        // 连续访问间隔过小，丢弃请求
        return Promise.resolve();
    }
    cacheInfo.last = now;
    const {_cache: cacheTime = Max_Time, forceLoad, _key = key} = ops;
    if (!forceLoad && cacheInfo.cache && now - cacheInfo.cache < cacheTime) {
        const data = get(getState(), _key);
        if (data) {
            return Promise.resolve(data);
        }
    }
    cacheInfo.cache = now;
    dispatch(action);
};


/**
 * 检查缓存项
 * @param keys
 * @param cb
 * @param ops
 */
export const check = (module, keys, cb) => (dispatch, getState) => {
    const now = new Date();
    const state = getState();
    const cacheData = {};
    const ks = reduce(keys, (res, val, key) => {
        const cacheKey = module + '_' + key;
        const cacheInfo = _cache[cacheKey] || (_cache[cacheKey] = {});
        const cacheTime = Max_Time;
        if (cacheInfo.cache && now - cacheInfo.cache < cacheTime) {
            const data = get(state, val);
            if (data) {
                cacheData[key] = data;
            } else {
                cacheInfo.cache = now;
                res.push(key);
            }
        } else {
            cacheInfo.cache = now;
            res.push(key);
        }
        return res;
    }, []);

    const re = cb(ks, cacheData);
    if (!ks.length) {
        return re;
    }
    dispatch(re);
};
